<?

include_once "core.class.php";

@session_start();
define("REDIRECT",1); #redir to page, 0 = show form from here
define("USEMYSQL",1); #0=no,1=yes 
define("USEFILE",0); #0=no,1=yes
define("FILEPATH","~.users"); #0=no,1=yes
define("USE_ENCRYPTION",0); #0=no,1=yes
define("VAR_TYPE","session"); # session/cookie
#define("VAR_TYPE","cookie");
define("SHOW_TOP_BAR",0);

#######
$x = parse_ini_file('../cfg/config.php', 1);

$xhost = $x['DB']['hostspec'];
$xuser = $x['DB']['username'];
$xdb   = $x['DB']['database'];
$xpass = $x['DB']['password'];
$prj   = $x['system']['prj_title'];
$httproot = $x['system']['http_root'];

$mylogin = '
<div id="main_null">
<div id="main">
  
  <div id="top">

   <div>
    Server: <b>
'.$_SERVER['SERVER_ADDR'].'</b> 
   </div>
  </div>
  
  <div id="title">
   <img src="img/title_1.png" alt="Control Panel Authentication page" />
   <h3>
    <span>Control Panel Authentication page</span>

   </h3>
  </div>

  <div id="cont">
<FORM NAME="login" ACTION="'.$PHP_SELF.'?show=login" METHOD=POST>

    <div class="win_null" style="width: 360px; margin-left: 70px;">
     <div class="win">
      <div class="win_title">
       <div>

        <h4>'.$prj.' Users Login</h4>
       </div>
      </div>
      <div class="win_body">

       <div class="sign">
        <table>
         <tr>
          <td>Username:</td>

          <td><input class="text1" type="text" name="username" /></td>
         </tr>
         <tr>
          <td>Password:</td>
          <td><input class="text1" type="password" name="password" /></td>
         </tr>
        </table>

       </div>
        
      </div>
      <div class="win_bottom">
       <div>
       </div>
      </div>
     </div> 
    </div>
    
    <p style="margin-left: 311px;">

     <input class="button1" type="submit" value="Login" />
    </p>
  <div id="title">
  </div>
  <div id="title">
  </div>
  <div id="title">
  </div>
  <div id="title">
  </div>
   </form>  
  </div>';


define("SHOW_LOGIN_FORM","
<html>
<head>
<title>$prj Users Login </title>
<link href=\"styles/login.css\" rel=\"stylesheet\" type=\"text/css\">
</head>
<body>
$mylogin
</body>
</html>
"); #show login form
define("REDIRECT_AFTER_LOGIN", "./"); #redirect to after login {$PHP_SELF}
define("FAILED_LOGIN","
    <br><br><center><h2>Login failed - <a href=\"$PHP_SELF?show=form\">go back</a></h2></center><br><br>
"); #failed login page
define("LOGOUT","$PHP_SELF?logout=true"); #logout page

define("LOGIN_MYSQL_HOST", "$xhost");
define("LOGIN_MYSQL_USER", "$xuser");
define("LOGIN_MYSQL_PASS", "$xpass");
define("LOGIN_MYSQL_DB", "$xdb");

define("LOGIN_MYSQL_TABLE", "resellers");
define("LOGIN_MYSQL_USERFIELD", "username"); // whatever field you use for username
define("LOGIN_MYSQL_PASSFIELD", "password"); // whatever field you use for password

define("ADMIN_FIELD","permission"); // this is for determining if admin or not
define("ADMIN_FIELD_VALUE", "99"); // the value that determines if admin or not

define ("DB_ERROR_PAGE", "<h3>Cannot connect to the database server.</h3>n");
define ("DB_ERROR", "<h3>Cannot connect to the database selected.</h3>n");

define("DEBUG","false"); // true=debug; false=no

// loginDatabaseConnect(LOGIN_MYSQL_HOST,LOGIN_MYSQL_USER,LOGIN_MYSQL_PASS,LOGIN_MYSQL_DB);
function loginDatabaseConnect($host, $user, $pass, $db) {
    if (!($mylink = mysql_connect($host, $user, $pass))){
            print  DB_ERROR_PAGE;
            #print mysql_error();
            exit('Unable to connect to database server.');
        }//fi
        mysql_select_db($db) or die('Unable to select database.');
}// end function

function object_to_cookie($obj){
    $z = serialize($obj);
    $z = gzcompress($z);
    $z = base64_encode($z);
    $z = urlencode($z);
  return $z;
}

function cookie_to_object($cookie){
    $z = urldecode($cookie);
    $z = base64_decode($z);
    $z = gzuncompress($z);
    $z = unserialize($z);
  return $z;
} 

function array2cookie($arr){
    while (list($key, $val)= each($arr)){
        sec_setcookie($key, $val);
        $key = $val;
        global ${$key};
    }//rof
}//end function

//main cookie function
function sec_setcookie($var, $val, $modify=3600){
    if (USE_ENCRYPTION == 1){ $val = object_to_cookie($val); }
    $exp = gmstrftime("%A, %d-%b-%Y %H:%M:%S", time()+$modify);
    $dom = $GLOBALS["HTTP_HOST"];
    if (preg_match("/^(.*):(.*)$/",$dom,$arr)) {
//        print_r($arr);
        $dom = $arr[1];
    }
    $parts = explode(".",$dom);
    $dom = ".".$parts[count($parts)-2].".".$parts[count($parts)-1];
    setcookie($var,$val, time()+$modify,"/",$dom, 0);
    ${$var} = $val;
    global ${$var};
}//end function

function check_login(){
    global $r_loggedin;
   if ( (isset($_COOKIE["r_loggedin"])&&isset($_COOKIE["r_username"])&&isset($_COOKIE["r_password"])) || $r_loggedin){
        return true;
    }else{
          if (!headers_sent()){
            # for if we want to redirect instead...
//            header("Location: ". SHOW_LOGIN_FORM);
            echo SHOW_LOGIN_FORM;
            //header("Location: http://www.yoursite.com/login.php");
            exit;
        }else{
            //echo "n<br><br><center><a href='".SHOW_LOGIN_FORM."'>CLICK HERE</a> to login</a></center><br><br>n";
            echo SHOW_LOGIN_FORM;
//            header("Location: http://www.yoursite.com/login.php");

            exit;
        }//fi        
    }//fi
}//end function


function do_login($username, $password){
    if (USE_ENCRYPTION == 1){ 
        $password = cookie_to_object($password); 
    }//fi
    loginDatabaseConnect(LOGIN_MYSQL_HOST, LOGIN_MYSQL_USER, LOGIN_MYSQL_PASS, LOGIN_MYSQL_DB);
             $sql = "SELECT * FROM ". LOGIN_MYSQL_TABLE
                                ." WHERE ". LOGIN_MYSQL_USERFIELD ."='".$username
                                ."' AND ". LOGIN_MYSQL_PASSFIELD ."='".$password."'";
        $tmp = mysql_query($sql)or die(DB_ERROR . mysql_error());
        if ( mysql_num_rows($tmp)>0 ){
            
            if (USE_ENCRYPTION == 1){ $password = object_to_cookie($password); }
            $row = mysql_fetch_array($tmp);

            $_SESSION["r_username"] = $username;
            $_SESSION["r_password"] = $password;
            $_SESSION["r_loggedin"] = true;
            $_SESSION["r_permission"] = $row[ADMIN_FIELD];

            
            sec_setcookie("r_username", $username);
            sec_setcookie("r_password", $password);
            sec_setcookie("r_loggedin", "true");
            sec_setcookie("r_permission", $row[ADMIN_FIELD]);

            if ($row[ADMIN_FIELD] == ADMIN_FIELD_VALUE){
                sec_setcookie("admin", "true");
                $_SESSION["r_admin"] = true;
                $_SESSION["r_permission"] = $row[ADMIN_FIELD];

            }//fi
   
            header("Location: ". REDIRECT_AFTER_LOGIN);
            exit;
        }else{
            sec_setcookie("r_username", "");
            sec_setcookie("r_password", "");
            sec_setcookie("r_loggedin", "");
            sec_setcookie("r_permission", "");

            $_SESSION["r_username"] = "";
            $_SESSION["r_password"] = "";
            $_SESSION["r_loggedin"] = false;
            $_SESSION["r_permission"] = "";

//          echo FAILED_LOGIN;
            header("Location: ./");
            exit;
            
        }//fi
}//end function

function show_logout(){
    return "<a href=\"".LOGOUT."\">logout</a>";
}//end function

############################################################################################
###########               below runs each time this file is accessed             ###########
############################################################################################
//echo "p=$p";
$show = $_GET['show'];
if ($p <> "signup"){
switch ($show){
    case "login":
        do_login($HTTP_POST_VARS["username"], $HTTP_POST_VARS["password"]);
        print_r($_GET);
        print_r($_POST);
        check_login();
        break;
    case "form":
        check_login();
        break;
    default:
        check_login();
        break;
}//switch
}//fi
###########
#echo "test";
if ($HTTP_POST_VARS["logout"] <> "" || $HTTP_GET_VARS["logout"] <> ""){
    while(list($key, $val) = each($_COOKIE)){
        sec_setcookie($key, "");
        $_SESSION["r_username"] = "";
        $_SESSION["r_password"] = "";
        $_SESSION["r_loggedin"] = false;
        $_SESSION = array();
    }//wend
    //header("Location: ". REDIRECT_AFTER_LOGIN);
    header("Location: ./");
}//
############################################################################################

if (SHOW_TOP_BAR == 1 && _disptop <> false){
?><body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width"100%" align="right">
    [ <span>Currently Logged in as:</span> <span ><? echo $username ?></span>
    | <? echo show_logout(); ?> ] </span> 
    </td>

  </tr>
</table>
<?
}//end function

?>
